import axios from "axios";
import Qs from "qs";

const cart={
  namespaced: true,
  state:()=>{
    return{
      item_list:[],
      item_id_list:[],
      cartUrl:'/cart/itemlist',
      wishUrl:'/wish/itemlist',
      order_id:'',
      address_id:''
    }
  },
  mutations:{

  },
  actions:{
    getCart({ state, commit, rootState }){
      /**
       *  TODO:查询购物车内商品
       */
      let getListUrl=state.cartUrl;
      if(rootState.user.type_id === 2){
        getListUrl = state.wishUrl
      }
      return new Promise((resolve, reject) =>{
        axios.get(getListUrl).then((res)=>{
          state.item_list = res.data;
          state.item_list.splice(0,0)
          resolve()
        }).catch(e=>{
          reject()
        })
      })
    },
    deleteItem({ state, commit, rootState }){
      /**
       *  TODO:删除购物车内商品
       */
      let delListUrl = '/cart/delete';
      if(rootState.user.type_id === 2){
        delListUrl = '/wish/delete'
      }
      return new Promise(((resolve, reject )=>{
        axios.post(delListUrl,
          Qs.stringify({item_id_list:state.item_id_list},{arrayFormat:'repeat'}),
          {
            headers: {
              'content-type': 'application/x-www-form-urlencoded;charset=utf-8'
            }
          })
          .then((res)=>{
            // state.order_id = res.data.order_id;
            resolve();
          }).catch(e=>{
          reject();
        })
      }))
    },
    buyItem({ state, commit, rootState }){
      /**
       *  TODO:在购物车下单
       */
      return new Promise(((resolve, reject )=>{
        axios.post('/cart/buy',
          Qs.stringify({item_id_list:state.item_id_list},{arrayFormat:'repeat'}),
          {
            headers: {
              'content-type': 'application/x-www-form-urlencoded;charset=utf-8'
            }
          })
          .then((res)=>{
          state.order_id = res.data.order_id;
          resolve();
        }).catch(e=>{
          reject();
        })
      }))
    },
    cartInitOrder({ state, commit, rootState}){
      /**
       *  TODO:支付并更新
       */
      let tempObj = {
        order_id:state.order_id,
        address_id:state.address_id
      }
      console.log('addressid',state.address_id);

      let obj = Qs.stringify({item_id_list:state.item_id_list},{arrayFormat:'repeat'})+'&'+Qs.stringify(tempObj);
      console.log(obj)
      return new Promise(((resolve, reject )=>{
        axios.post('/cart/initorder',obj).then(()=>{
          resolve()
        }).catch(e=>[
          reject()
        ])
      }))
    }
  }
}

export default cart;
